<template>
  <div class="product-selection-container">
    <!-- 左侧分类列表 -->
    <div class="category-sidebar">
      <div 
        class="category-item" 
        :class="{ active: selectedCategoryId === null }"
        @click="selectCategory(null)"
      >
        全部
      </div>
      <div 
        class="category-item" 
        v-for="category in categoryList" 
        :key="category.categoryId"
        :class="{ active: selectedCategoryId === category.categoryId }"
        @click="selectCategory(category.categoryId)"
      >
        {{ category.name }}
      </div>
    </div>

    <!-- 右侧内容区域 -->
    <div class="main-content">
      <!-- 搜索框 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="searchProducts"
        >
          <template #append>
            <el-button icon="Search" @click="searchProducts"></el-button>
          </template>
        </el-input>
      </div>

      <!-- 商品列表 -->
      <div class="product-list">
        <div 
          class="product-card" 
          v-for="product in productList" 
          :key="product.productId"
        >
          <div class="product-image">
            <image-preview 
              v-if="product.imageUrl" 
              :src="product.imageUrl" 
              :width="100" 
              :height="100"
            />
            <div v-else class="no-image">暂无图片</div>
          </div>
          <div class="product-info">
            <div class="product-name">{{ product.name }}</div>
            <div class="product-price">¥{{ product.price }}</div>
            <div class="product-actions">
              <el-input-number
                v-model="product.quantities"
                :min="0"
                :max="product.stock"
                size="small"
                @change="updateCart(product)"
              />
              <el-button 
                type="primary" 
                size="small" 
                @click="addToCart(product)"
                :disabled="!product.quantities || product.quantities <= 0"
              >
                加入购物车
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 购物车按钮 -->
      <div class="cart-button" @click="openCart">
        <el-badge :value="cartItems.length" :max="99" v-if="cartItems.length > 0">
          <el-button type="primary" icon="ShoppingCart">购物车</el-button>
        </el-badge>
        <el-button v-else type="primary" icon="ShoppingCart">购物车</el-button>
      </div>

      <!-- 购物车弹窗 -->
      <el-drawer
        v-model="showCart"
        title="购物车"
        direction="rtl"
        size="400px"
      >
        <div class="cart-content">
          <div v-if="cartItems.length === 0" class="empty-cart">
            购物车为空
          </div>
          <div v-else>
            <div 
              class="cart-item" 
              v-for="(item, index) in cartItems" 
              :key="item.cartId || index"
            >
              <div class="cart-item-image">
                <image-preview 
                  v-if="item.imageUrl" 
                  :src="item.imageUrl" 
                  :width="50" 
                  :height="50"
                />
                <div v-else class="no-image-small">无图</div>
              </div>
              <div class="cart-item-info">
                <div class="cart-item-name">{{ item.name }}</div>
                <div class="cart-item-price">¥{{ item.price }}</div>
              </div>
              <div class="cart-item-quantity">
                <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="item.stock"
                  size="small"
                  @change="updateCartItemQuantity(index, item)"
                />
              </div>
              <div class="cart-item-total">
                ¥{{ (item.price * item.quantity).toFixed(2) }}
              </div>
              <div class="cart-item-remove">
                <el-button 
                  type="danger" 
                  icon="Delete" 
                  circle 
                  size="small" 
                  @click="removeFromCart(index, item)"
                />
              </div>
            </div>
            
            <div class="cart-summary">
              <div class="total-price">
                总价: <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
              </div>
              <div class="cart-actions">
                <el-button @click="clearCart">清空购物车</el-button>
                <el-button type="primary" @click="submitOrder">提交订单</el-button>
              </div>
            </div>
          </div>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { listCategory } from "@/api/manage/category"
import { listProduct, getProduct } from "@/api/manage/product"  // 添加 getProduct
import { getCurrentInstance } from 'vue'
import { addCart, listCart, updateCart as updateCartApi, delCart } from "@/api/manage/cart"
import { clearCart as clearCartApi } from "@/api/manage/cart"
import { getUserId } from "@/api/manage/center"
import { getMerchantByUserId } from "@/api/manage/merchant"
// 导入订单相关的API
import { addOrder } from "@/api/manage/order"

const merchantId = ref(null)
const merchantInfo = ref(null) // 存储商家信息
const { proxy } = getCurrentInstance()

const categoryList = ref([])
const productList = ref([])
const showCart = ref(false)
const selectedCategoryId = ref(null)
const cartItems = ref([])

// 搜索参数
const searchQuery = reactive({
  name: '',
  categoryId: null
})

// 获取商品分类列表
function getCategoryList() {
  listCategory().then(response => {
    categoryList.value = response.data || response.rows || []
  }).catch(err => {
    console.error('获取商品分类失败:', err)
  })
}

// 获取商品列表
function getProductList() {
  const params = {
    ...searchQuery,
    pageNum: 1,
    pageSize: 100 // 获取较多商品
  }
  
  // 如果选择了分类，设置分类ID
  if (selectedCategoryId.value !== null) {
    params.categoryId = selectedCategoryId.value
  }
  
  listProduct(params).then(response => {
    // 为每个商品添加数量属性
     productList.value = (response.rows || [])
      .filter(product => {
        // 只显示上架商品(status为1)
        return product.status === 1;
      })
      .map(product => ({
        ...product,
        quantities: 0
      }))
  }).catch(err => {
    console.error('获取商品列表失败:', err)
  })
}

// 选择分类
function selectCategory(categoryId) {
  selectedCategoryId.value = categoryId
  searchQuery.categoryId = categoryId
  getProductList()
}

// 搜索商品
function searchProducts() {
  getProductList()
}

// 添加到购物车
function addToCart(product) {
  if (!product.quantities || product.quantities <= 0) return
  
  // 使用获取到的商家ID
  const cartData = {
    merchantId: merchantId.value,
    productId: product.productId,
    number: product.quantities,
    amount: product.price * product.quantities,
    image: product.imageUrl
  }
  
  addCart(cartData).then(response => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess("已添加到购物车")
      // 重置商品数量选择
      product.quantities = 0
      // 如果购物车窗口打开，则刷新购物车数据
      if (showCart.value) {
        getCartList()
      }
    } else {
      proxy.$modal.msgError("添加购物车失败")
    }
  }).catch(err => {
    console.error('添加购物车失败:', err)
    proxy.$modal.msgError("添加购物车失败")
  })
}

// 更新购物车（当数量改变时）
function updateCart(product) {
  // 这里可以做一些实时更新的操作，如果需要的话
}

// 修改 openCart 函数，确保商家ID已获取后再打开购物车
async function openCart() {
  showCart.value = true;
  
  // 确保商家ID已获取
  if (!merchantId.value) {
    // 等待商家ID获取完成，设置一个超时时间
    let attempts = 0;
    const maxAttempts = 10;
    
    while (!merchantId.value && attempts < maxAttempts) {
      await new Promise(resolve => setTimeout(resolve, 100));
      attempts++;
    }
  }
  
  // 获取购物车列表
  getCartList();
}

// 修改 getCartList 函数 - 添加获取商品名称的逻辑
function getCartList() {
  // 确保商家ID已获取
  if (!merchantId.value) {
    console.warn('商家ID尚未获取，无法查询购物车数据')
    return
  }
  
  // 直接传递 merchantId 作为参数
  listCart(merchantId.value).then(response => {
    if (response.code === 200) {
      // 获取商品详细信息以确保有商品名称
      const cartItemsWithProductInfo = response.rows.map(item => ({
        ...item,
        quantity: item.number,
        price: item.number > 0 ? item.amount / item.number : 0,
        imageUrl: item.image
      }));
      
      // 为每个购物车项获取商品名称
      Promise.all(cartItemsWithProductInfo.map(item => {
        return getProduct(item.productId).then(productResponse => {
          if (productResponse.code === 200) {
            item.name = productResponse.data.name; // 设置商品名称
            item.productName = productResponse.data.name; // 兼容性设置
          }
          return item;
        }).catch(() => {
          // 如果获取商品信息失败，使用现有名称或默认名称
          item.name = item.name || '未知商品';
          return item;
        });
      })).then(items => {
        cartItems.value = items;
      });
    }
  }).catch(err => {
    console.error('获取购物车列表失败:', err)
    proxy.$modal.msgError("获取购物车数据失败")
  })
}

// 更新购物车项数量
function updateCartItemQuantity(index, item) {
  if (item.quantity <= 0) {
    removeFromCart(index, item)
    return
  }
  
  // 更新购物车中商品的数量
  const updateData = {
    cartId: item.cartId,
    merchantId: item.merchantId,
    productId: item.productId,
    number: item.quantity,
    amount: item.price * item.quantity,
    image: item.image
  }
  
  updateCartApi(updateData).then(response => {
    if (response.code !== 200) {
      proxy.$modal.msgError("更新购物车失败")
    }
  }).catch(err => {
    console.error('更新购物车失败:', err)
    proxy.$modal.msgError("更新购物车失败")
  })
}

// 从购物车移除
function removeFromCart(index, item) {
  if (item.cartId) {
    delCart(item.cartId).then(response => {
      if (response.code === 200) {
        cartItems.value.splice(index, 1)
        proxy.$modal.msgSuccess("已从购物车移除")
      } else {
        proxy.$modal.msgError("移除失败")
      }
    }).catch(err => {
      console.error('删除购物车项失败:', err)
      proxy.$modal.msgError("移除失败")
    })
  } else {
    cartItems.value.splice(index, 1)
  }
}

// 修改 clearCart 函数
// 修改 clearCart 函数，只清空当前商家的商品
function clearCart() {
  if (cartItems.value.length > 0) {
    // 使用已获取的商家ID而不是从购物车商品中获取
    if (merchantId.value) {
      clearCartApi(merchantId.value).then(response => {
        if (response.code === 200) {
          // 只移除当前商家的商品，而不是清空整个购物车
          cartItems.value = cartItems.value.filter(item => item.merchantId !== merchantId.value)
          proxy.$modal.msgSuccess("购物车已清空")
        } else {
          proxy.$modal.msgError("清空购物车失败")
        }
      }).catch(err => {
        console.error('清空购物车失败:', err)
        proxy.$modal.msgError("清空购物车失败")
      })
    } else {
      // 如果没有获取到商家ID，尝试从购物车商品中获取（备选方案）
      const merchantIdFromCart = cartItems.value[0].merchantId;
      if (merchantIdFromCart) {
        clearCartApi(merchantIdFromCart).then(response => {
          if (response.code === 200) {
            // 只移除当前商家的商品
            cartItems.value = cartItems.value.filter(item => item.merchantId !== merchantIdFromCart)
            proxy.$modal.msgSuccess("购物车已清空")
          } else {
            proxy.$modal.msgError("清空购物车失败")
          }
        }).catch(err => {
          console.error('清空购物车失败:', err)
          proxy.$modal.msgError("清空购物车失败")
        })
      }
    }
  }
}

// 修改后的 getMerchantInfo 函数
function getMerchantInfo() {
  getUserId().then(response => {
    // 根据您的描述，response应该直接是一个数字(userId)
    if (typeof response === 'number') {
      const userId = response;
      // 使用用户ID获取商家信息
      getMerchantByUserId(userId).then(merchantResponse => {
        if (merchantResponse.code === 200) {
          merchantId.value = merchantResponse.data.merchantId;
          merchantInfo.value = merchantResponse.data; // 保存商家信息
        }
      }).catch(err => {
        console.error('获取商家信息失败:', err)
      })
    } else if (response.code === 200 && response.rows && response.rows.length > 0) {
      // 保留原有的处理逻辑作为备选方案
      const userId = response.rows[0].userId;
      getMerchantByUserId(userId).then(merchantResponse => {
        if (merchantResponse.code === 200) {
          merchantId.value = merchantResponse.data.merchantId;
          merchantInfo.value = merchantResponse.data; // 保存商家信息
        }
      }).catch(err => {
        console.error('获取商家信息失败:', err)
      })
    }
  }).catch(err => {
    console.error('获取用户ID失败:', err)
  })
}

// 提交订单 - 新增功能
function submitOrder() {
  if (cartItems.value.length === 0) {
    proxy.$modal.msgWarning("购物车为空")
    return
  }

  // 构造订单数据
  const orderData = {
    // merchantId 从 merchantInfo 获取
    merchantId: merchantInfo.value ? merchantInfo.value.merchantId : null,
    merchantName: merchantInfo.value ? merchantInfo.value.name : '',
    merchantAddress: merchantInfo.value ? merchantInfo.value.address : '',
    merchantPhone: merchantInfo.value ? merchantInfo.value.phone : '',
    status: 1, // 订单状态：1-待处理
    orderNumber: generateOrderNumber(), // 生成订单号
    empId: null, // 员工ID，初始为空
    regionId: merchantInfo.value ? merchantInfo.value.regionId : null, // 所属区域
    tbOrderDetailList: cartItems.value.map(item => ({
      productId: item.productId,
      productName: item.name || item.productName || '未知商品', // 使用商品名称
      number: item.quantity,
      unitPrice: item.price,
    }))
  };

  // 调用API创建订单
  addOrder(orderData).then(response => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess("订单提交成功");
      // 清空购物车
      clearCart();
      // 关闭购物车弹窗
      showCart.value = false;
    } else {
      proxy.$modal.msgError("订单提交失败: " + response.msg);
    }
  }).catch(err => {
    console.error('提交订单失败:', err);
    proxy.$modal.msgError("订单提交失败");
  });
}

// 生成订单号
function generateOrderNumber() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  
  return `${year}${month}${day}${hours}${minutes}${seconds}${random}`;
}

// 计算总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0)
})

onMounted(() => {
  getCategoryList()
  getProductList()
  getMerchantInfo() // 添加这行来获取商家信息
})

</script>

<style scoped>
.product-selection-container {
  display: flex;
  height: calc(100vh - 120px);
  background-color: #f5f5f5;
}

.category-sidebar {
  width: 200px;
  background-color: #fff;
  border-right: 1px solid #ebeef5;
  padding: 20px 0;
  overflow-y: auto;
}

.category-item {
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.3s;
  border-left: 3px solid transparent;
}

.category-item:hover {
  background-color: #f5f5f5;
}

.category-item.active {
  background-color: #ecf5ff;
  color: #409eff;
  border-left-color: #409eff;
}

.main-content {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.search-bar {
  margin-bottom: 20px;
  width: 300px;
}

.product-list {
  flex: 1;
  overflow-y: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.product-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 15px;
  text-align: center;
  transition: transform 0.3s;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-image {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
}

.no-image {
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #999;
  border-radius: 4px;
}

.product-info {
  text-align: center;
}

.product-name {
  font-size: 14px;
  margin-bottom: 8px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.product-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.cart-button {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 1000;
}

.cart-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.empty-cart {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 16px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.cart-item-image {
  width: 50px;
  height: 50px;
  margin-right: 10px;
}

.no-image-small {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #999;
  font-size: 12px;
  border-radius: 4px;
}

.cart-item-info {
  flex: 1;
  margin-right: 10px;
}

.cart-item-name {
  font-size: 14px;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cart-item-price {
  color: #f56c6c;
  font-size: 14px;
}

.cart-item-quantity {
  width: 100px;
  margin-right: 10px;
}

.cart-item-total {
  width: 80px;
  text-align: right;
  color: #f56c6c;
  font-weight: bold;
  margin-right: 10px;
}

.cart-item-remove {
  width: 30px;
}

.cart-summary {
  margin-top: auto;
  padding: 20px;
  border-top: 1px solid #eee;
}

.total-price {
  font-size: 18px;
  margin-bottom: 20px;
  text-align: right;
}

.price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 20px;
}

.cart-actions {
  display: flex;
  justify-content: space-between;
}
</style>